package load;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet(name = "DownloadServlet", value = "/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//      获取下载文件名
        String downloadFileName = "download.jpeg";
//      读取要下载的文件内容
        ServletContext servletContext = getServletContext();
//        获取要下载的文件类型
        servletContext.getMimeType("/file/" + downloadFileName);
//      告诉客户端数据类型
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
            //用于处理中文名
        //如果是火狐浏览器用Base编码
        if(request.getHeader("User-Agent").contains("Firefox")){
        response.setHeader("Content-Disposition", "attachment;filename==?UTF-8?B?"+new BASE64Encoder().encode("中文.jpeg".getBytes(StandardCharsets.UTF_8)));
        }else {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("中文.jpeg","UTF-8"));
        }
//      映射的代码web目录
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
//      获取响应的输出流
        OutputStream outputStream = response.getOutputStream();
//      读取输入流中全部的数据，复制给输出流
        IOUtils.copy(resourceAsStream, outputStream);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
